<template>
	<view class="container">
		<!-- 状态栏占位 -->
		<view class="status-bar" :style="{ height: statusBarHeight + 'px' }"></view>


		<view class="photos-container">
			<view class="waterfall">
				<view class="waterfall-column" v-for="(column, columnIndex) in photoColumns" :key="columnIndex">
					<view class="photo-item" v-for="(photo, index) in column" :key="index"
						@click="previewImage(photo.url, columnIndex, index)">
						<view class="skeleton" v-if="!photo.loaded" :style="{ height: photo.estimatedHeight + 'px' }">
						</view>
						<image v-if="photo.url" :src="photo.url" mode="widthFix" :style="{
							width: '100%',
							opacity: photo.loaded ? 1 : 0,
							transition: 'opacity 0.3s ease'
						}" @load="(e) => onImageLoad(columnIndex, index, e)" @error="(e) => console.error('图片加载失败:', photo.url, e)" />
					</view>
				</view>
			</view>
		</view>
	</view>
</template>

<script setup lang="ts">
import { onMounted, ref } from 'vue';

// 获取状态栏高度
const statusBarHeight = ref(uni.getSystemInfoSync().statusBarHeight)
// 设置导航栏高度（通常是44px）
const navBarHeight = ref(44)

// 修改类型定义
interface PhotoItem {
	url: string;
	loaded: boolean;  // 改为 boolean 而不是固定的 false
	height?: number; // 添加高度属性
	width?: number;  // 添加宽度属性
	estimatedHeight?: number; // 添加预估高度属性
}

// 修改照片数据的类型声明
const photos = ref<PhotoItem[]>([])

// 获取婚纱照数据
const fetchPhotos = async () => {
	try {
		const response: any = await uni.request({
			url: 'https://vue.bigtian.club/prod-api//system/weddingPhotos/getResource',
			method: 'GET',
			data: {
				type: 'index-banner'
			}
		});

		// 处理响应数据
		if (response.statusCode === 200 && response.data) {
			const imageUrls = response.data.data || [];
			console.log('获取到的图片数据:', imageUrls);

			// 设置一个默认的预估宽高比（例如 4:3）
			const defaultAspectRatio = 0.75;
			const screenWidth = uni.getSystemInfoSync().windowWidth;
			const columnWidth = screenWidth * 0.47;
			const estimatedHeight = columnWidth * defaultAspectRatio;

			photos.value = imageUrls.map((item: any) => {
				const imageUrl = typeof item === 'object' ? item.url || '' : item;
				return {
					url: imageUrl,
					loaded: false,
					width: 0,
					height: 0,
					estimatedHeight: estimatedHeight // 添加预估高度
				};
			}).filter(photo => photo.url);

			console.log('处理后的照片数据:', photos.value);
			initializePhotos();
		}
	} catch (error) {
		console.error('获取婚纱照失败:', error);
		uni.showToast({
			title: '获取照片失败',
			icon: 'none'
		});
	}
}

onMounted(() => {
	fetchPhotos();
})

// 分成两列
const COLUMN_COUNT = 2
const photoColumns = ref<PhotoItem[][]>([[], []])

// 记录列高度
const columnHeights = ref([0, 0])

// 优化的初始化照片分布
const initializePhotos = () => {
	photoColumns.value = [[], []];
	columnHeights.value = [0, 0];

	// 随机打乱照片顺序以获得更自然的分布
	const shuffledPhotos = [...photos.value].sort(() => Math.random() - 0.5);

	shuffledPhotos.forEach(photo => {
		const minHeightIndex = columnHeights.value[0] <= columnHeights.value[1] ? 0 : 1;
		photoColumns.value[minHeightIndex].push(photo);
		columnHeights.value[minHeightIndex] += photo.estimatedHeight!;
	});
}

// 优化图片加载完成的处理
const onImageLoad = (columnIndex: number, index: number, event: any) => {
	const photo = photoColumns.value[columnIndex][index];
	if (photo) {
		try {
			// 获取图片实际宽高比
			const { width, height } = event.detail;
			photo.width = width;
			photo.height = height;
			photo.loaded = true;

			// 计算图片在列中的实际显示高度
			const screenWidth = uni.getSystemInfoSync().windowWidth;
			const columnWidth = screenWidth * 0.47;
			const displayHeight = (height / width) * columnWidth;

			// 当前图片加载完成后，重新计算布局
			reflow();
		} catch (error) {
			console.error('图片加载处理错误:', error);
		}
	}
}

// 重新计算布局
const reflow = () => {
	// 获取所有已加载的图片
	const loadedPhotos = photos.value.filter(photo => photo.loaded);
	const unloadedPhotos = photos.value.filter(photo => !photo.loaded);

	// 清空现有列
	photoColumns.value = [[], []];
	columnHeights.value = [0, 0];

	const screenWidth = uni.getSystemInfoSync().windowWidth;
	const columnWidth = screenWidth * 0.47;

	// 先处理已加载的图片
	loadedPhotos.forEach(photo => {
		const displayHeight = (photo.height! / photo.width!) * columnWidth;
		const minHeightIndex = columnHeights.value[0] <= columnHeights.value[1] ? 0 : 1;
		photoColumns.value[minHeightIndex].push(photo);
		columnHeights.value[minHeightIndex] += displayHeight;
	});

	// 处理未加载的图片，也按照预估高度分配到较短的列
	unloadedPhotos.forEach(photo => {
		const minHeightIndex = columnHeights.value[0] <= columnHeights.value[1] ? 0 : 1;
		photoColumns.value[minHeightIndex].push(photo);
		columnHeights.value[minHeightIndex] += photo.estimatedHeight!;
	});

	console.log('重新布局完成，列高度：', columnHeights.value);
}

// 预览图片
const previewImage = (url: string, columnIndex: number, index: number) => {
	const urls = photos.value.map(photo => photo.url).filter(url => url); // 过滤掉空URL
	const current = url;
	if (urls.length > 0) {
		uni.previewImage({
			urls,
			current
		});
	}
}
</script>

<style lang="scss" scoped>
.container {
	background-color: #fff;
	min-height: 100vh;
}

.status-bar {
	width: 100%;
	background-color: #fff;
}

.nav-bar {
	width: 100%;
	background-color: #fff;
	display: flex;
	align-items: center;
	justify-content: center;

	.title {
		font-size: 32rpx;
		font-weight: 500;
		color: #333;
	}
}

.photos-container {
	padding: 20rpx;
	box-sizing: border-box;

	.waterfall {
		display: flex;
		justify-content: space-between;
		padding: 0 20rpx;

		.waterfall-column {
			width: 47%;

			.photo-item {
				margin-bottom: 20rpx;
				border-radius: 16rpx;
				overflow: hidden;
				position: relative;

				.skeleton {
					width: 100%;
					background: #f0f0f0;
					border-radius: 16rpx;
					position: relative;
					overflow: hidden;

					&::after {
						content: '';
						position: absolute;
						top: 0;
						left: 0;
						right: 0;
						bottom: 0;
						background: linear-gradient(90deg,
								rgba(255, 255, 255, 0) 0%,
								rgba(255, 255, 255, 0.3) 50%,
								rgba(255, 255, 255, 0) 100%);
						transform: translateX(-100%);
						animation: shimmer 2s cubic-bezier(0.4, 0, 0.2, 1) infinite;
					}
				}

				image {
					display: block;
					width: 100%;
					height: auto;
					vertical-align: bottom;
					opacity: 0;
					transition: opacity 0.3s ease;

					&[src] {
						opacity: 1;
					}
				}
			}
		}
	}
}

// 优化骨架屏动画
@keyframes skeleton-loading {
	0% {
		background-position: 100% 50%;
	}

	100% {
		background-position: 0 50%;
	}
}

// 优化闪光效果动画
@keyframes shimmer {
	0% {
		transform: translateX(-150%);
	}

	100% {
		transform: translateX(150%);
	}
}

// 边缘发光动画
@keyframes borderGlow {
	0% {
		opacity: 0.5;
	}

	50% {
		opacity: 1;
	}

	100% {
		opacity: 0.5;
	}
}
</style>
